package com.vote.www.controller;

import com.vote.www.core.page.Pagination;
import com.vote.www.service.SortingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 汤伟杰 on 2017/5/18.
 */
@Controller
@RequestMapping("/sorting")
public class SortingController {
    @Autowired
    private SortingService sortingService;

    /**
     *
     * @param req
     * @param resp
     * @param model
     * @return
     */
    @RequestMapping({"/list.do",""})
    public String list(
            HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        model.addAttribute("msg", req.getParameter("msg"));
        Pagination pagination = sortingService.list();
        model.addAttribute("pagination", pagination);
        return "sorting/list";
    }

    /**
     * 排序位置交换
     * @param req
     * @param resp
     * @param model
     */
    @RequestMapping("/exchange.do")
    public String exchange(@RequestParam(required = true) Integer sorting,
                         @RequestParam(required = true) String id,
            HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = "";
        try {
            if(sorting==1||sorting==-1){
                sortingService.exchange(id,sorting);
                map.put("status", "1");
            }else{
                throw new Exception("参数sorting只能传-1或1");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", "0");
            msg =""+ e.getMessage();
//            map.put("msg", e.getMessage());
        }
        return "redirect:list.do?msg="+msg;
//        resp.getWriter().print(JSONObject.toJSONString(map));

    }
}
